<template>
  <div class="store-layou">
    <div class="header">
      <div class="header_span">
        <cell-header title="关键词库" :type="1"></cell-header>
    </div>
    </div>
    <div class="word-main">
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <!-- 公共词库开始 -->
        <el-tab-pane v-if="teamId" v-loading="commonLoading" label="团队词库" name="commonality" element-loading-text="公共词库数据加载中">
          <el-row v-if="commonStore.length" :gutter="24">
            <el-col v-for="(item,index) in commonStore" :key="item.wordUserId" :md="8" :lg="6" :xl="4" :sm="12" :xs="12">
              <word-box
                class="word-box"
                :store-info="item"
                @del="handleDelWordStore"
                @edit="modifyWordStore"
                @copy="handleCopyWordStore"
                @addTo="handleAddToWherr"
              ></word-box>
            </el-col>
          </el-row>

          <div v-else style="width: 100%;text-align: center;padding: 15vh;">
            <span style=" color: rgb(144, 147, 153);font-size: 14px;">暂无数据,快去创建吧</span>
          </div>
        </el-tab-pane>
        <!-- 公共词库结束 -->

        <!-- 个人词库 -->
        <el-tab-pane v-loading="myLoading" label="个人词库" name="personage" element-loading-text="个人词库数据加载中">
          <el-row v-if="privateStore.length" :gutter="24">
            <el-col v-for="(item,index) in privateStore" :key="item.wordUserId" :md="8" :lg="6" :xl="4" :xs="12">
              <word-box
                class="word-box"
                type="personage"
                :store-info="item"
                @del="handleDelWordStore"
                @edit="modifyWordStore"
                @copy="handleCopyWordStore"
                @addTo="handleAddToWherr"
              ></word-box>
            </el-col>
          </el-row>
          <div v-else style="width: 100%;text-align: center;padding: 15vh;">
            <span style=" color: rgb(144, 147, 153); font-size: 14px;">暂无数据,快去创建吧</span>
          </div>
        </el-tab-pane>
      </el-tabs>

      <el-button class="add-btn" type="success" size="small" @click="handleAddWordStore">创建词库</el-button>
    </div>

    <el-dialog title="创建词库" :visible.sync="dialogFormVisible" width="548px" @close="handleCloseCreate">
      <el-form ref="createForm" :model="form" size="small" label-position="top" :rules="rules">
        <el-form-item label="词库名称" prop="name">
          <el-input v-model.trim="form.name" autocomplete="off" style="width: 380px;" placeholder="请输入词库名称"></el-input>
        </el-form-item>
        <el-form-item label="创建至" prop="teamId">
          <el-select v-model="form.teamId" placeholder="请选择词库类型">
            <el-option label="个人词库" :value="''"></el-option>
            <el-option v-if="teamId" label="公共词库" :value="teamId"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button class="cancel-btn defult" @click="handleCloseCreate">取 消</el-button>
        <el-button type="success" class="defult" :disabled="subLoading" @click="handleSubCreate">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import cellHeader from '@/components/cell-header.vue'
import wordBox from './components/wordBox.vue'

import {
  findWordStore, // 查询词库接口
  crateWordsGroup, // 创建词库接口
  reallocate // 词库重名验证
} from '@/api/tool.js'

export default {
  name: '', // ·������
  components: {
    cellHeader,
    wordBox
  },
  data() {
    var validateSerialName = (rule, value, callback) => {
      var regTextChar = /^[\u4e00-\u9fa5A-Za-z0-9\-\_]*$/
      if (value === '') {
        callback(new Error('请输入词库名称'))
      } else {
        const flag = regTextChar.test(value)
        const reg = new RegExp(/\s/g) // 清空字符自中所有空格
        if (!flag || reg.test(value)) return callback(new Error('只能由汉字,字母,数字,下划线,横杠组成'))

        const obj = {
          name: value,
          teamId: this.form.teamId
        }
        reallocate(obj).then(res => {
          // console.log(res, '重名验证')
          if (res.data.code * 1 === 20000) {
            return callback()
          } else {
            return callback(new Error('词库名称不得重复'))
          }
        })
      }
    }
    return {
      timer: undefined,
      activeName: 'commonality',
      dialogFormVisible: false,
      privateStore: [], // 私人词库
      myLoading: false,
      commonStore: [], // 公共词库
      commonLoading: false,
      subLoading: false,
      form: {
        name: '',
        teamId: ''
      },
      rules: {
        name: [{
          required: true,
          message: '请输入词库名称',
          trigger: 'blur'
        },
        {
          min: 3,
          max: 20,
          message: '长度在 3 到 20个字符',
          trigger: 'blur'
        },
        {
          validator: validateSerialName,
          trigger: 'blur'
        }
        ]
      }
    }
  },
  computed: {
    teamId() {
      return this.$store.state.team.teamId
    }
  },
  watch: {
    // obj: { //�����Ķ���
    //   deep: true, //���ȼ�������Ϊ true
    //   // ������wacth��������firstName��������֮��������ȥִ��handler����
    //       immediate: true
    //   handler: function(newV, oldV) {
    //     console.log('watch�У�', newV)
    //   }
    // }
  },
  // ������
  created() {},
  // ���غ�
  mounted() {
    if (this.teamId) {
      this.activeName = 'commonality'
      this.findWordStoreByTeam(this.teamId)
    } else {
      this.activeName = 'personage'
      this.findWordStoreByTeam('')
    }
  },
  // ���ٺ�
  destroyed() {

  },

  // ����
  methods: {
    handleClick(type) {
      if (this.timer) {
        clearTimeout(this.timer)
      }
      this.timer = setTimeout(() => {
        if (this.activeName === 'personage') {
          this.findWordStoreByTeam('')
        } else {
          this.findWordStoreByTeam(this.teamId)
        }
      }, 800)
    },

    // 查询公共词库与查询个人词库
    async findWordStoreByTeam(teamId) {
      if (teamId) {
        this.commonLoading = true
      } else {
        this.myLoading = true
      }
      const obj = {
        page: 1,
        size: 2000,
        teamId
      }
      const teamStr = teamId ? '个人词库' : '公共词库'
      try {
        const res = await findWordStore(obj)
        if (teamId) {
          this.commonLoading = false
        } else {
          this.myLoading = false
        }
        this.$message.closeAll()
        if (res.data.code * 1 === 20000) {
          const {
            list
          } = res.data.data
          if (teamId) {
            this.commonStore = JSON.parse(JSON.stringify(list))
          } else {
            this.privateStore = JSON.parse(JSON.stringify(list))
          }
        } else {
          this.$message({
            duration: 1500,
            message: res.data.message || teamStr + '查询失败',
            type: 'error'
          })
        }
      } catch (err) {

      }
    },

    handleAddWordStore() {
      if (this.activeName === 'personage') {
        this.form.teamId = ''
      } else {
        this.form.teamId = this.teamId
      }
      this.dialogFormVisible = true
    },

    handleCloseCreate() {
      this.$refs['createForm'].resetFields()
      this.$nextTick(() => {
        this.dialogFormVisible = false
      })
    },
    handleSubCreate() {
      this.$refs['createForm'].validate(async(valid) => {
        if (valid) {
          this.subLoading = true
          try {
            const res = await crateWordsGroup(this.form)
            this.subLoading = false
            this.$message.closeAll()
            if (res.data.code * 1 === 20000) {
              this.$message({
                duration: 1500,
                message: res.data.message || '创建词库成功',
                type: 'success'
              })
              this.findWordStoreByTeam(this.form.teamId)
              this.handleCloseCreate()
            } else {
              this.$message({
                duration: 1500,
                message: res.data.message || '创建词库失败',
                type: 'error'
              })
            }
          } catch (err) {

          }
        } else {
          return false
        }
      })
    },

    // 创建词库副本成功之后的函数
    handleCopyWordStore(data) {
      this.findWordStoreByTeam(data.teamId)
    },
    // 删除词库
    handleDelWordStore(data) {
      this.findWordStoreByTeam(data.teamId)
    },
    // 下载词库
    handleDownWordStore() {},
    // 添加至
    handleAddToWherr() {},
    // 修改词库
    modifyWordStore() {}

  }
}
</script>

<style scoped lang="scss">
.header {
  width: 100%;
  height: 70px;
  position: fixed;
  // left: 0;
  margin-top: -25.7px;
  z-index: 99;
  background: #f9f9f9;
  .header_span {
    position: absolute;
    margin-top: 24px;
    // margin-left: 105px;
  }
}
  .word-main {
    position: relative;
    // top: -10px;
    // top: 45px;
    top:45px;
    margin-bottom: 50px;
    .add-btn {
      position: absolute;
      right: 0;
      top: 0;
      font-size: 14px;
    }
  }
</style>
